package com.wxyzz.satserver.websocket;


import com.fasterxml.jackson.databind.ObjectMapper;

import com.wxyzz.common.core.entity.User;
import com.wxyzz.common.core.utils.UserUtils;
import com.wxyzz.satserver.component.OnlineUserManager;
import com.wxyzz.satserver.friend.entity.vo.FriendVO;
import com.wxyzz.satserver.message.dao.MessageMapper;
import com.wxyzz.satserver.message.dao.MessageSessionMapper;
import com.wxyzz.satserver.message.entity.Message;
import com.wxyzz.satserver.websocket.ReqResController.MessageRequset;
import com.wxyzz.satserver.websocket.ReqResController.MessageResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Controller

public class WebsocketController extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private MessageMapper messageMapper;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("[WebSocketController] 连接成功");
        User user =  (User) session.getAttributes().get("user");
        if(user == null){
            return;
        }

        onlineUserManager.online(user.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("[webSocketController] 收到消息"+ message.toString());
        //处理消息的接收,转发,以及消息的保存记录
        User user = (User) session.getAttributes().get("user");
        if(user == null){
            System.out.println("[WebSocketController] user == null 未登录用户,无法进行消息的转发");
            return;
        }
        MessageRequset req = objectMapper.readValue(message.getPayload(),MessageRequset.class);
        if(req.getType().equals("message")){
            transferMessage(user,req);
        }else {
            System.out.println("[WebSocket] req.type 有误"+ message.getPayload());
        }

    }

    private void transferMessage(User fromuser, MessageRequset req) throws IOException {
        //1.先构造一个待转发的响应对象,MessageResponse
        MessageResponse resp = new MessageResponse();
        resp.setType("message");
        resp.setFromId(fromuser.getId());
        resp.setFromName(fromuser.getUsername());
        resp.setSessionId(req.getSessionId());
        resp.setContent(req.getContent());
        //把这个java对象转成json格式字符串
        String respJson = objectMapper.writeValueAsString(resp);
        System.out.println("[transferMessage] respJson"+respJson);

        //2.根据请求中的sessionId,获取到这个MessageSession 里都有那些用户.通过查询数据库就能够知道
        List<FriendVO> friends = messageSessionMapper.getFriendsBySessionId(req.getSessionId(),fromuser.getId());
        //把当前用户添加到上述List里面
        FriendVO myself = new FriendVO();
        myself.setFriendId(fromuser.getId());
        myself.setFriendName(fromuser.getUsername());
        friends.add(myself);
        //3.循环遍历上述的这个列表,给列表中的每个用户都发送一份响应消息
        // 知道每个用户的userId,进一步的查询刚才准备好的OnlineUserManager,就知道对应的WebSocketSession
        // 从而进行发送消息
        // 注意:除了给查询到的好友们发,给自己发一个,方便实现在自己的客户端上 显示自己发送的消息
        for (FriendVO friend:friends) {
            //知道每个用户的userId,进一步的查询刚才准备好的OnlineUserManager,就知道了对应的WebScoketSession
            //从而进行发送消息
            WebSocketSession webSocketSession = onlineUserManager.getSession(friend.getFriendId());
            if(webSocketSession == null){
                //如果该用户未在线,则不发送
                continue;
            }

            webSocketSession.sendMessage(new TextMessage((respJson)));
        }
        //4.转发的消息,还需要放到数据库里,后续用户下线之后,重新上线,可以通过历史消息的方式拿到之前的消息
        Message message = new Message();
        message.setFromId(fromuser.getId());
        message.setSessionId(req.getSessionId());
        message.setContent(req.getContent());
//        messageMapper.add(message);

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("[WebSocketController] 连接异常" + exception.toString());
        User user =  (User) session.getAttributes().get("user");
        if(user == null){
            return;
        }
        onlineUserManager.offline(user.getId(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("[WebSocketController]"+status.toString());
        User user =  (User) session.getAttributes().get("user");
        if(user == null){
            return;
        }
        onlineUserManager.offline(user.getId(),session);
    }
}

